#pragma once


#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <unistd.h>
#include <pthread.h>
#include "task.hpp"
#include "Thread.hpp"

const static int N = 5;


template<class T>
class ThreadPool
{
public:
    ThreadPool(int num = N) :_num(num)
    {
        pthread_mutex_init(&_lock,nullptr);
        pthread_cond_init(&_cond,nullptr);
    }
    void lockQueue()
    {
        pthread_mutex_lock(&_lock);
    }
    void unlockQueue()
    {
        pthread_mutex_unlock(&_lock);
    }
    void threadWait()
    {
        pthread_cond_wait(&_cond,&_lock);
    }
    void threadWakeup()
    {
        pthread_cond_signal(&_cond);
    }
    bool isEmpty()
    {
        return _tasks.empty();
    }
    T popTask()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
    static void* threadRoutine(void* args)
    {
        pthread_detach(pthread_self());
        ThreadPool<T>* tp = (ThreadPool*)(args);
        while(true)
        {
            tp->lockQueue();
            while(tp->isEmpty())
            {
                tp->threadWait();
            }
            T t = tp->popTask();
            tp->unlockQueue();

            t();
            std::cout << "thread handler done, result: " << t.formatRes() << std::endl;
        }
    }
    void init()
    {
        for(int i=0;i<_num;++i)
        {
            _thread.push_back(Thread(i,threadRoutine,this));
        }
    }
    void start()
    {
       for(auto& t:_thread)
       {
            t.run();
       }
    }
    void check()
    {
        for(auto& t:_thread)
        {
            std::cout<<t.threadname()<<"running"<<std::endl;
        }
    }
    void pushTask(const T& t)
    {
        lockQueue();
        _tasks.push(t);
        threadWakeup();
        unlockQueue();
    }
    ~ThreadPool()
    {
        for(auto& t:_thread)
        {
            t.join();
        }
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
private:
    std::vector<Thread> _thread;
    int _num;
    std::queue<T> _tasks;
    pthread_mutex_t _lock;
    pthread_cond_t _cond;
};